package de.fhhannover.inform.itteam.snmpnetviz.snmp;

import java.util.List;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

public class SnmpAdapter {
	private Address mTargetAddress;
	private CommunityTarget mTarget;
	private Snmp mSnmp;
	
	public SnmpAdapter(String address,String community) {
		try {
			mTargetAddress = GenericAddress.parse(address);
			TransportMapping transport;
			transport = new DefaultUdpTransportMapping();
			mSnmp = new Snmp(transport);
			USM usm = new USM(SecurityProtocols.getInstance(),new OctetString(MPv3.createLocalEngineID()), 0);
			SecurityModels.getInstance().addSecurityModel(usm);
			transport.listen();
			
			// setting up target
		   mTarget = new CommunityTarget();
		   mTarget.setCommunity(new OctetString(community));
		   mTarget.setAddress(mTargetAddress);
		   mTarget.setRetries(2);
		   mTarget.setTimeout(500);
		   mTarget.setVersion(SnmpConstants.version2c);  
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<TableEvent> getTable(OID tableOid) {
		TableUtils tableutil = new TableUtils(mSnmp, new DefaultPDUFactory());
		return tableutil.getTable(mTarget, new OID[] {tableOid}, null, null);
	}
	
	public VariableBinding getOid(OID oid,int getType) {
		try {
		// create the PDU
		   PDU pdu = new PDU();
		   pdu.add(new VariableBinding(oid));
		   pdu.setType(getType);

		   return mSnmp.send(pdu, mTarget).getResponse().get(0);
		} catch (Exception e) {}
		return null;
	}
	
}
